import React, { Component } from 'react'
import { Form, Input, Button, message } from 'antd'
import axios from '../Utils/axios'

class NormalForm extends Component {
    constructor (props) {
        super(props)
        this.state = {
            nextImage: this.props.nextImage,
            imageToken: this.props.imageToken,
            userName: '',
            phone: '',
            imgCode: '',
            verCode: '',
            sendStatus: 60,
            msgSend: true
        }
    }

    _saveState = () => {
        const { phone, imgCode, verCode } = this.props.form.getFieldsValue()
        this.setState({
            phone: phone,
            imgCode: imgCode,
            verCode: verCode
        })
    }

    componentWillUnmount () {
        clearInterval(window.timer)
    }

    _handlerSubming = e => {
        e.preventDefault()
        this.props.form.validateFieldsAndScroll((err, values) => {
            if (!err) {
                this.props.hideModal()
                this.props.showNext(this.state)
            }
        })
    }

    _getImagCode = () => {
        axios({
          method: 'post',
          url: '/api/sso/account/imgCode'
        })
        .then(data => {

            if (data.status !== 'success') {
                message.error(data.errorReason)
                return
            }
            data = JSON.parse(data.result)
            if (data.result === 'success') {
                this.setState({
                    nextImage: data.imaCode,
                    imageToken: data.imgtoken
                })
            } else {
                message.error(data.reason)
            }
        })
      }

    _sendMsg = (type, e) => {
        const msgSend = this.state.msgSend
        const { phone, imgCode } = this.props.form.getFieldsValue()
        const targetElement = e.target

        if(!phone) {
            message.error('手机号码未填写')
            return
        }

        if(!imgCode) {
            message.error('图形验证码不能为空')
            return
        }

        if (phone && imgCode) {
            if (!msgSend) {
                message.info('短信验证码已发送，请稍后再试')
                return
            }
            window.timer = setInterval(() => {
                if (this.state.sendStatus > 0) {
                    this.setState({sendStatus: (this.state.sendStatus)-1})
                    targetElement.innerHTML = `${this.state.sendStatus}s后重试`
                } else {
                    clearInterval(window.timer)
                    targetElement.innerHTML = `发送短信验证码`
                    this.setState({sendStatus: 60})
                    targetElement.addEventListener('click', this._sendMsg(1, e), false)
                    this.setState({msgSend: true})
                }

            }, 1000)
            this.setState({msgSend: false})
            message.success('短信验证码已发送，如未收到请60s后重试')

            axios({
            method: 'post',
            url: '/api/sso/account/sendCode',
            data: JSON.stringify({ "phone": phone, type: type, 'imgCode': imgCode, 'imgtoken': this.state.imageToken })
            })
            .then(data => {
                message.destroy()
                if (data.status !== 'success') {
                    message.success(data.reason || '短信发送失败！')
                    return
                }
                data = JSON.parse(data.result)
                if (data.result === 'success') {
                    message.info(data.reason || '短信发送成功！')
                    this.setState({
                        userName: data.username
                    })
                } else {
                    message.info(data.reason || '短信发送失败！')
                }
                })
        }
    }


    componentDidMount () {}

    render () {
        const { getFieldDecorator } = this.props.form
        const { nextImage } = this.state
        return (
                <Form onSubmit={this._handlerSubming}>
                    <Form.Item className={`register_form_item`}>
                        {getFieldDecorator('phone', {
                        validateTrigger: 'onBlur',
                        rules: [{ required: true, message: '手机号码不能为空!' }, {
                            validator: (rule, value, callback) => {
                                if (!value) {
                                    callback()
                                    return
                                }
                                if (value.length < 11) {
                                    callback('请输入正确的手机号码')
                                    return
                                }

                                if (!(/\d(3|4|5|6|7|8|9)\d(\d{4})(\d{4})/ig.test(value))) {
                                  callback('请输入正确的手机号码')
                                  return
                                }

                                callback()
                            }
                        }],
                        })(
                        <Input
                            maxLength={11}
                            className='user-modal-default phone-input-set'
                            prefix={<span className="user-label-register">手&nbsp;机&nbsp;号&nbsp;码&nbsp;：</span>}
                            placeholder="请输入手机号码"
                            allowClear={true}
                        />,
                        )}
                    </Form.Item>
                    <Form.Item className={`register_form_item`}>
                        {
                            getFieldDecorator('imgCode', {
                                rules: [{ required: true, message: '图形验证码不能为空！'}]
                            })(
                                <Input
                                maxLength={5}
                                className='user-modal-default image-code'
                                prefix={<span className="user-label-register">图形验证码：</span>}
                                placeholder='请输入图形验证码'
                                allowClear={true}
                                 />
                            )
                        }
                        <div className='image-validate'>
                            <img src={nextImage ? 'data:image/png;base64,'+nextImage : ''} alt="" onClick={() => {this._getImagCode()}} />
                        </div>
                    </Form.Item>
                    <Form.Item className={`register_form_item`}>
                        {getFieldDecorator('verCode', {
                        rules: [{ required: true, message: '短信验证码不能为空!' }],
                        })(
                        <Input
                            maxLength={5}
                            className='user-modal-default image-code'
                            prefix={<span className="user-label-register">短信验证码：</span>}
                            onBlur={() => {this._saveState()}}
                            placeholder="请输入短信验证码"
                            allowClear={true}
                        />,
                        )}
                        <div className='image-validate send-msg-button' onClick={(e) => {this._sendMsg(1, e)}}>
                            发送验证码
                        </div>
                    </Form.Item>
                    <Form.Item>
                        <Button type="primary" htmlType="submit" className="register-button">
                            下一步
                        </Button>
                    </Form.Item>
                </Form>
        )
    }
}

const WrapperNormalForm = Form.create()(NormalForm)

export default WrapperNormalForm
